package com.example.bookreader1130_1203.ui.dashboard;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.bookreader1130_1203.Adapter.BookAdapter;
import com.example.bookreader1130_1203.Bean.Book;
import com.example.bookreader1130_1203.Bean.ChooseBook;
import com.example.bookreader1130_1203.R;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class DashboardFragment extends Fragment {
    private ListView chooselv ;
    private BookAdapter adapter;
    List<Book>  bookList =new ArrayList<>();
    List<ChooseBook> chooseBookList =new ArrayList<>();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dashboard, container, false);

        initData();/*填充数据*/
        initView(view);
        setListener();
        return view;
    }

    private void setListener() {
        chooselv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                /*收藏页面*/
                int cid = chooseBookList.get(position).getId();
                LitePal.delete(ChooseBook.class,cid);
                chooseBookList.remove(position);
                bookList.remove(position);
                adapter.notifyDataSetChanged();
                showToast("删除成功");
                /* AIT+回车 在目标里创建一个方法*/

                return false;
            }
        });

    }

    private void showToast(String str) {
        Toast.makeText(getContext(),str,Toast.LENGTH_SHORT).show();
    }

    private void initData() {/*填充初始数据*/
        SharedPreferences sp=getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        int uid =sp.getInt("userid",-1);  /*这里获取uid用户id*/
        /*获取与张三有关的所有信息*/       //多表查询典例
        chooseBookList = LitePal.where("userid=?",uid+"")
                .find(ChooseBook.class);
        for (ChooseBook c:chooseBookList){//遍历
            Book b =LitePal.find(Book.class,c.getBookid()) ;
            /*找到这张表*/
            bookList.add(b);
        }
    }

    private void initView(View view ) {
        chooselv=view.findViewById(R.id.chooselv);
        /*   */

        adapter=new BookAdapter(getContext(),R.layout.book_item,bookList);
        chooselv.setAdapter(adapter);


    }
}